<?php
/*
 * 前端控制器类
 * 单例类
 * 
 * PHP 4.0以上支持
 * @since 1.0
 * 
 */
class FontController {
	
	protected $_controller;	//对应$_actionAction.class.php
	protected $_action;	//对应$_actionAction.class.php中的$_method方法
	protected $_params;
	protected $_body;
	protected $_frame;
	static $_instance;	//保存该类得自身对象
	
	private function __construct(){
		$this->analyzeRequest();
		//$this->checkurl();
	}
	private function __clone(){
		
	}
	
	public static function getInstance(){
		if (!(self::$_instance instanceof self)){
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function analyzeRequest(){
		//获取用户请求的URL
		$request_url = $_SERVER['REQUEST_URI'];
		//分析URL并保存为数组Array ( [0] => user [1] => add [2] => id=3 )
		$splits = explode('/',trim($request_url,'/'));
		
		//把数组中的值赋值给controller和action，如果为空返回Index寻找默认controller或者默认方法
		$this->_controller = !empty($splits[0])?$splits[0].'Controller':'IndexController';
		$this->_action = !empty($splits[1])?$splits[1].'Action':'IndexAction';
		//判断数组中时候有action和method之外的其他参数
		if (!empty($splits[2])){
			$keys = $values = array();
			for ($idx=2,$cnt=count($splits);$idx<$cnt;$idx++){
				if ($idx %2 ==0){
					//偶数索引号指定的事键值
					$keys[] = $splits[$idx];
				}else {
					//奇数索引号指定的事数值
					$values[] = $splits[$idx];
				}
			}
			$this->_params = array_combine($keys,$values);
		}
	}
	
	public function route(){
		//如果该Controller类已经定义
		if (class_exists($this->getController())){
			//获取Controller类的信息保存到$rc
			$rc = new ReflectionClass($this->getController());
			if ($rc->implementsInterface('ControllerInterface')){
				//如果这个类中有对应的方法则运行，否则提示错误
				if ($rc->hasMethod($this->getAction())){
					//新建Controller类的对象
					$controller = $rc->newInstance();
					$method = $rc->getMethod($this->getAction());
					$method->invoke($controller);
				}else {
					echo "has no this action";
				}
			}else {
				echo "this controller is not implements IController Interface";	
			}
		}else {
			echo "has no this controller";
		}
	}
	
	
	public function getParams(){
		return $this->_params;
	}
	
	public function getController(){
		return (String)$this->_controller;
	}
	
	public function getAction(){
		return $this->_action;
	}
	
	public function setBody($body){
		$this->_body = $body;
	}
	
	public function getBody(){
		return $this->_body;
	}
	
	public function setFrame($frame){
		ob_start();
		$this->_frame = $frame;
		return ob_get_clean();
	}
	
	public function getFrame(){
		return $this->_frame;
	}
	
/*
	 * 来路检查函数
	 * 过滤URL中的method=xxx$id=xxx等用户输入的非法地址，并跳转到网站首页
	 * 
	 * PHP4.0以上支持
	 * @since 1.0
	 * 
	 */
	public function checkurl() {
		if (preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) {
			header("Location: http://www.google.com");
			exit();
		}
	}
}